package com.example.lxq.demo.controller;

import java.io.File;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import com.example.lxq.demo.config.SpringObserver;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PreviewController {

    @GetMapping("gethtmls")
    public ArrayList<String> getHtmls(String dir){
        // File file=new File("D:\\model space\\"+dir);
        File file=new File(SpringObserver.vPath+dir);
        System.out.println(dir);
        ArrayList<String> files=new ArrayList<>();
        String fileType[]={"html","css","jpg","jpeg","png","webp"};
        for(String item:file.list()){
            for(String type:fileType){
                if(item.toLowerCase().endsWith(type)){
                    files.add(item);
                    continue;
                }
            }
        }
        // Collections.sort(files,new Comparator<String>(){
        //     @Override
        //     public int compare(String o1, String o2) {
        //         if(o1.equals(o2))return 0; else return 1;
        //     }
        // });
        return files;
    }

    @GetMapping("getdirs")//http://localhost/getdirs
    public ArrayList<FileObj> getDirs(String from,HttpServletRequest request){
        // File file=new File("D:\\model space\\"+from);
        File file=new File(SpringObserver.vPath+from);
        System.out.println(request.getRemoteAddr()+"查看了"+from);
        
        if(from.equals("")){
            file=new File(SpringObserver.vPath);
            return generateJSON(file);
        }
        return generateJSON(file);
    }

    public ArrayList<FileObj> generateJSON(File file){
        File files[]=file.listFiles();
        ArrayList<FileObj> fileList=new ArrayList<>();
        for(File fileItem:files){
            FileObj obj=new FileObj();
            obj.setFileName(fileItem.getName());
            if(fileItem.isDirectory()){
                obj.setFileType(FileObj.DIRECTORY);
            }else{
                obj.setFileType(FileObj.FILE);
            }
            fileList.add(obj);
        }
        return fileList;
    }

    public static void main(String[] args) {
        File dir=new File("D:\\model space\\");
        for(String name:dir.list()){
            System.out.println(name);
        }
    }
}
class FileObj{
    private String fileName;
    private int fileType;

    public static int DIRECTORY=0;
    public static int FILE=1;

    public String getFileName() {
        return fileName;
    }
    public int getFileType() {
        return fileType;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    public void setFileType(int fileType) {
        this.fileType = fileType;
    }
}